<template>
  <div>
    <el-container>
      <span>本地地址</span>
      <el-col :span="8">
        <el-input v-model="localBasePath"></el-input>
      </el-col>
      <el-switch
        v-model="updateFlag"
        size="large"
        active-text="自动同步"
        inactive-text="关"
        @change="testInterval"
      />
      <el-switch
        v-model="autoRemoveFlag"
        size="large"
        active-text="自动删除"
        inactive-text="关"
      />
      <el-button @click="updateImgs">同步一次</el-button>
    </el-container>
  </div>
</template>

<script lang="ts">
import { ref } from "vue";
import type { Ref } from "vue";
import { ElMessage } from "element-plus";
import { updateFileInfoMysql } from "../api";

const path = require("path");
const fs = require("fs");
const Client = require("ftp");
const images = require("images");

export default {
  name: "FtpUpper",
  setup() {
    const updateFlag: Ref<boolean> = ref(false);
    const autoRemoveFlag: Ref<boolean> = ref(false);
    let timer: NodeJS.Timer | null = null;
    const localBasePath = ref("C:\\Users\\masaikk\\Desktop\\3");

    const updateImgs = () => {
      console.log("开始上传文件");
      let basePath = localBasePath.value;
      const tmpPath = path.join(basePath, "tmp");
      fs.exists(tmpPath, (exists: boolean) => {
        if (!exists) {
          fs.mkdir(tmpPath, (err: Error) => {
            if (err) {
              console.log(err);
            }
          });
        }
      });
      const pattern = new RegExp("[0-9]*-[0-9]*");
      let c = new Client();
      c.on("ready", () => {
        c.cwd("novalai", (err: Error) => {
          // prefix
          if (err) {
            console.log("error occur");
            throw err;
          }
        });
        fs.readdir(basePath, (err: Error, files: string[]) => {
          // console.log(files);
          files.pop(); //删除tmp文件夹
          console.log(files);
          files.forEach((file: string) => {
            // console.log(file); //文件名
            const fileFrontName = pattern.exec(file);
            const fileNameInFtp = fileFrontName + file.slice(file.length - 4);

            let fileTags: string = file.slice(
              JSON.stringify(fileFrontName).length - 3,
              file.length - 4
            );
            const totalPath = path.join(basePath, file);
            const fileNameInTmpFolder = fileFrontName + ".jpg";
            images(totalPath).save(path.join(tmpPath, fileNameInTmpFolder), {
              //Save the image to a file, with the quality of 50
              quality: 75,
            });
            debugger;
            c.put(totalPath, fileNameInFtp, (err: Error) => {
              console.log("put");
              if (err) {
                console.log("error");
                throw err;
              } else {
                updateFileInfoMysql(totalPath, fileNameInFtp, fileTags).then(
                  (res) => {
                    console.log(res);
                    if (autoRemoveFlag.value) {
                      ElMessage({
                        message: `文件 ${fileNameInFtp} 已经上传并在本地删除!`,
                        type: "success",
                      });
                      fs.unlinkSync(totalPath);
                    } else {
                      ElMessage({
                        message: `文件 ${fileNameInFtp} 已经上传!`,
                        type: "success",
                      });
                    }
                  }
                );
              }
            });
          });
        });
        c.cwd("../compress_novalai", (err: Error) => {
          // prefix
          if (err) throw err;
        });
        fs.readdir(tmpPath, (err: Error, files: string[]) => {
          // debugger;
          if (err) {
            console.log(err);
          } else {
            files.forEach((file: string) => {
              const tmpFileTotalName = path.join(tmpPath, file);
              c.put(tmpFileTotalName, file, (err: Error) => {
                if (err) {
                  console.log(err);
                  // throw err;
                } else {
                  fs.unlinkSync(tmpFileTotalName);
                  ElMessage({
                    message: `缩略文件 ${tmpFileTotalName} 已经上传!`,
                    type: "success",
                  });
                }
              });
            });
          }
        });

        c.end();
      });
      // fs.rmdirSync(tmpPath)
      c.connect({
        host: "server.masaikk.xyz",
        user: "b8313",
        password: "b8313",
      });
    };
    const testInterval = () => {
      if (updateFlag.value) {
        timer = setInterval(() => {
          updateImgs();
        }, 1000);
      } else {
        clearInterval(timer as NodeJS.Timer);
      }
      // console.log(1);
    };
    return {
      updateFlag,
      updateImgs,
      testInterval,
      localBasePath,
      autoRemoveFlag,
    };
  },
};
</script>

<style scoped></style>
